package com.czy.workflow.core.util;

import cn.hutool.json.JSONUtil;
import cn.hutool.script.ScriptUtil;
import com.czy.workflow.core.exception.FlowExpressionException;
import com.czy.workflow.core.model.TaskInfo;

import javax.script.CompiledScript;
import javax.script.ScriptException;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

public class ExpressionUtil {

    static Logger logger = Logger.getLogger(ExpressionUtil.class.getName());

    static List<String> trueFlags = Arrays.asList("T", "true", "True", "1");
    public static boolean exeExpression(String expression, TaskInfo taskInfo) throws FlowExpressionException {
        if(trueFlags.contains(expression)){
            return true;
        }
        String expParams = "var task = " + JSONUtil.toJsonStr(taskInfo) + ";";
        expression = expParams + expression;
        CompiledScript script = ScriptUtil.compile("function check(){"+expression+"}; check();");
        try {
            Object result = script.eval();
            return result == Boolean.TRUE;
        } catch (ScriptException e) {
            throw new FlowExpressionException(taskInfo);
        }
    }


}
